package io.netty.test.main.nio.classic;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Set;

/**
 * @author LuoYu
 * @date 2019/03/08 8:44
 * <p>
 * Description:
 * 简单的nio服务端
 */
public class SimpleChatServer {
    public static void main(String[] args) throws IOException {
        // =================初始化=====================
        // 创建一个ServerSocketChannel
        // 1.不能通过new来创建，而是通过open静态方法创建实例
        // 2.作为服务端处理io信息的通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 将通道设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        // 服务通道所属socket绑定端口
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        // 创建一个选择器线程
        Selector selector = Selector.open();
        // 将服务端通道注册到选择器上 监听事件为accept：存在可接受连接
        // 注册事件触发时，会生成一个对应事件类型的selection key
        // 监听时，使用selector.selectedKeys来得到当前注册通道的事件
        serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);
        // ====================监听========================
        while (true) {
            int eventNum = selector.select();
            if (eventNum > 0) {
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                for (SelectionKey selectionKey : selectionKeys) {
                    if (selectionKey.isValid() && selectionKey.isAcceptable()) {
                        //
                        ServerSocketChannel server = (ServerSocketChannel) selectionKey.channel();
                    } else if (selectionKey.isValid() && selectionKey.isReadable()) {
                        SocketChannel clientChannel = (SocketChannel) selectionKey.channel();
                    }
                }
            }
        }


    }
}
